﻿using Admin.NET.Application.ServiceTra.TraFaXues.Dto;

namespace Admin.NET.Application.Service;

/// <summary>
/// 输血申请发血主表
/// </summary>
public class TraFaXueService : BaseServiceBill<TraFaXue>
{
    private readonly SqlSugarRepository<TraFaXue> _traShenQingFaXueZhuBiaoRep;
    private readonly SqlSugarRepository<TraFaXueMingXi> _traShenQingFaXueMingXiRep;
    public TraFaXueService(
        IServiceScopeFactory scopeFactory,
        SqlSugarRepository<TraFaXue> traShenQingFaXueZhuBiaoRep,
        SqlSugarRepository<TraFaXueMingXi> traShenQingFaXueMingXiRep
    ) : base(scopeFactory)
    {
        _traShenQingFaXueZhuBiaoRep = traShenQingFaXueZhuBiaoRep;
        _traShenQingFaXueMingXiRep = traShenQingFaXueMingXiRep;
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<SqlSugarPagedList<TraFaXueOutput>> Page(BaseKeywordPageInput input)
    {
        var traShenQingFuHeList = await Queryable.FuzzyQuery(input.Keyword, new List<string> { "id" })
           .Select<TraFaXueOutput>()
           .OrderByDescending(it => it.Id)
           .ToPagedListAsync(input.Page, input.PageSize);

        return traShenQingFuHeList;
    }

    /// <summary>
    /// 通过Id获取
    /// </summary>
    public TraFaXueOutput Get(string id)
    {
        return GetById<TraFaXueOutput>(id);
    }

    /// <summary>
    /// 新增成功后返回主键
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public TraFaXue Add(FaXueAddInputDto input)
    {
        input.ZhuBiao.danJuZhuangTai = DanJuZhuangTai.已生效;
        input.ZhuBiao.danJuLeiXing = "临床发血";
        var result = AddWithInput(input.ZhuBiao);
        foreach (var mingXi in input.MingXiList)
        {
            mingXi.traFaXueId = result.Id;
        }
        _traShenQingFaXueMingXiRep.InsertRange(input.MingXiList.Adapt<List<TraFaXueMingXi>>());
        return result;
    }

    /// <summary>
    /// 更新成功后返回true
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    public bool Update(FaXueAddInputDto input)
    {
        var result = UpdateWithInput(input.ZhuBiao);
        _traShenQingFaXueMingXiRep.Delete(e => e.traFaXueId == input.ZhuBiao.Id);
        foreach (var mingXi in input.MingXiList)
        {
            mingXi.traFaXueId = input.ZhuBiao.Id;
        }
        _traShenQingFaXueMingXiRep.InsertRange(input.MingXiList.Adapt<List<TraFaXueMingXi>>());
        return result;
    }
    /// <summary>
    /// 修改发血主表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    public bool UpdateZhuBiao(TraFaXueInput input)
    {
        var result = UpdateWithInput(input);
        return result;
    }
}
